<?php

require_once __DIR__ . '/core.php';

// 取出请求参数
$lang = $con->request->get('lang');
$type = $con->request->get('type');

// 获取分类
$id = getCateType($type);
if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
            // 查询数据
            $data = $con->db->table('cate')->find('id, pid, c_name, c_url, c_img, c_on, c_re, c_sort')
                            ->where('c_lang = ?', [$lang])->order('c_sort ASC')->all();
            $data = $hel->listTree($data, $id);
            $cates = [];
            foreach ($data as $index => $cate) {
                $cates[$index]['seq'] = $index + 1;
                $cates[$index]['id'] = $cate['id'];
                $cates[$index]['name'] = generate_name($cate['level']) . $cate['c_name'];
                $cates[$index]['image'] = '<img id="image-' . ($index + 1) . '" src="' . loadImage($cate['c_img'], $hel) . '" alt="分类标识图" height="27">';
                $cates[$index]['on'] = '<input class="layui-form-switch" type="checkbox" value="启用" lay-skin="primary" ' . (1 == $cate['c_on'] ? 'checked' : '') . '>';
                $cates[$index]['re'] = '<input class="layui-form-switch" type="checkbox" value="推荐" lay-skin="primary" ' . (1 == $cate['c_re'] ? 'checked' : '') . '>';
                foreach (['url', 'sort'] as $key) {
                    $cates[$index][$key] = $cate['c_' . $key];
                }
            }
            unset($data);
            // 统计总数
            $count = $con->db->table('cate')->count();
            // 返回数据
            $data = [
                'msg' => '',
                'code' => 0,
                'count' => $count,
                'data' => $cates
            ];
            $con->json($data);
            break;
        case 'open':
        case 'recommend':
            // 取出唯一标识
            $unique = $con->request->post('unique');
            // 查询开启状态
            $field = $action == 'recommend' ? 'c_re' : 'c_on';
            $on = $con->db->table('cate')->find($field)->where('id = ?', [$unique])->one();
            if (!$on) {
                break;
            }
            if (1 == $on[$field]) {
                $row = $con->db->table('cate')->update([$field => 0], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => false]);
                } else {
                    $con->json(['code' => false, 'stat' => true, 'err' => '关闭失败']);
                }
            } else {
                $row = $con->db->table('cate')->update([$field => 1], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => true]);
                } else {
                    $con->json(['code' => false, 'stat' => false, 'err' => '开启失败']);
                }
            }
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('cate')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $data = $con->request->post(['pid', 'name', 'url', 'kwd', 'des', 'img', 'details', 'on', 're', 'sort']);
            // 处理数据
            $cate = verify_data($data);
            unset($data);
            if (!is_array($cate)) {
                $con->json(['code' => false, 'err' => $cate]);
                break;
            }
            // 修改数据
            $row = $con->db->table('cate')->update($cate, 'id = ?', [$unique])->row();
            $code = 1 === $row;
            $url = $hel->path() . '/cate.php?lang=' . $lang . '&type=' . $type;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '修改失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'insert':
            // 取出数据
            $data = $con->request->post(['pid', 'name', 'url', 'kwd', 'des', 'img', 'details', 'on', 're', 'sort']);
            // 处理数据
            $cate = verify_data($data);
            unset($data);
            if (!is_array($cate)) {
                $con->json(['code' => false, 'err' => $cate]);
                break;
            }
            $cate['c_lang'] = $lang;
            // 插入数据
            $row = $con->db->table('cate')->insert($cate)->row();
            $code = 1 === $row;
            $url = $hel->path() . '/cate.php?lang=' . $lang . '&type=' . $type;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '添加失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'upload':
            // 取出文件名
            $unique = $con->request->post('unique');
            $name = null;
            $image = new \sc\Upload();
            if ($image->isImage()) {
                $path = $image->save('file/category', $name);
                if (!$path) {
                    $con->json(['code' => false, 'err' => '保存失败']);
                } else {
                    $con->json(['code' => true, 'path' => $path]);
                }
            } else {
                $con->json(['code' => false, 'err' => '请上传图片文件']);
            }
            break;
        default:break;
    }
} else {
    $action = $con->request->get('action');
    if ('edit' == $action) {
        // 获取唯一标识
        $unique = $con->request->get('unique');
        // 查询数据
        $data = $con->db->table('cate')->find('id, pid, c_name, c_url, c_kwd, c_des, c_img, c_details, c_on, c_re, c_sort')->where('id = ?', [$unique])->one();
        $cate = [];
        $cate['id'] = $data['id'];
        $cate['pid'] = $data['pid'];
        $cate['img'] = loadImage($data['c_img'], $hel, false);
        foreach (['name', 'url', 'kwd', 'des', 'details', 'on', 're', 'sort'] as $index) {
            $cate[$index] = $data['c_' . $index];
        }
        unset($data);
        $categories = $con->db->table('cate')->find('id, pid, c_name')->where('c_lang = ?', [$lang])->order('c_sort ASC')->all();
        $categories = $hel->listTree($categories, $id, 1);
        // 获取顶级分类
        $parent_cat = $con->db->table('cate')->find('id, pid, c_name')->where('id = ?', [$id])->one();
        $parent_cat['level'] = 0;
        array_unshift($categories, $parent_cat);
        $con->render('cate-edit', [
            'hel' => $hel,
            'crumb' => $breadcrumb,
            'select' => generate_select($categories, 'pid', $cate['pid']),
            'cate' => $cate,
            'host' => $hel->url(),
            'path' => $hel->path(),
            'lang' => $lang,
            'type' => $type
        ]);
    } else if ('insert' == $action) {
        $data = false;
        $categories = $con->db->table('cate')->find('id, pid, c_name')->where('c_lang = ?', [$lang])->order('c_sort ASC')->all();
        $categories = $hel->listTree($categories, $id, 1);
        // 获取顶级分类
        $parent_cat = $con->db->table('cate')->find('id, pid, c_name')->where('id = ?', [$id])->one();
        $parent_cat['level'] = 0;
        array_unshift($categories, $parent_cat);
        $con->render('cate-edit', [
            'hel' => $hel,
            'crumb' => $breadcrumb,
            'select' => generate_select($categories, 'pid', 0),
            'cate' => $data,
            'host' => $hel->url(),
            'path' => $hel->path(),
            'lang' => $lang,
            'type' => $type
        ]);
    } else {
        $con->render('cate', [
            'crumb' => $breadcrumb,
            'host' => $hel->url(),
            'path' => $hel->path(),
            'lang' => $lang,
            'type' => $type
        ]);
    }
}

function getCateType($type) {
    // 获取分类
    switch ($type) {
        case 'product':$id = 1;
            break;
        case 'info':$id = 2;
            break;
        case 'media':$id = 3;
            break;
        case 'vidoes':$id = 7;
            break;
        default:$id = 1 << 16 - 1;
            break;
    }
    return $id;
}

// 生成分类名称方法
function generate_name($level) {
    $name = '';
    while ($level--) {
        if ($level > 0) {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        } else {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;|__&nbsp;&nbsp;';
        }
    }
    return $name;
}

// 生成分类菜单方法
function generate_select($categories, $name, $pid) {
    $html = '<select name="' . $name . '" lay-filter="' . $name . '">';
    foreach ($categories as $category) {
        $html .= '<option value="' . $category['id'] . '" ' . ($pid == $category['id'] ? 'selected' : '') . '>' . generate_name($category['level']) . $category['c_name'] . '</option>';
    }
    return $html . '</select>';
}

/**
 * 数据验证方法
 *
 * @param array $data
 *
 * @return string|array
 */
function verify_data($data) {
    $cate['pid'] = $data['pid'];
    if ('' == $data['name']) {
        // 名称为空
        return '分类名称不能为空';
    }
    $cate['c_name'] = $data['name'];
    if ('' != $data['url']) {
        // URL不为空
        if (is_numeric($data['url'])) {
            return 'URL不能为纯数字';
        }
        $cate['c_url'] = preg_replace('/[^-0-9a-zA-Z]+/', '-', $data['url']);
    }
    foreach (['kwd', 'des', 'img', 'details'] as $index) {
        $cate['c_' . $index] = $data[$index];
    }
    if ((int) $data['sort'] < 0) {
        // 排序小于0
        return '分类排序必须大于0';
    }
    $cate['c_sort'] = $data['sort'];
    if (null != $data['on']) {
        $cate['c_on'] = 1;
    } else {
        $cate['c_on'] = 0;
    }
    if (null != $data['re']) {
        $cate['c_re'] = 1;
    } else {
        $cate['c_re'] = 0;
    }

    return $cate;
}
